<?php
/**
 * @Author: king
 * @Last Modified by:   king
 * Date: 2018/6/13
 * Time: 11:45
 */

namespace App\Models\Api;
use App\Models\Api\Base;
use Cache;

class Fortunenote extends Base
{

    protected $table = 'fortune_note';  
    public $timestamps = false;

    /**
     * 运势笔记所有ids
     */
    const REDIS_KEY_FORTUNE_NOTE_IDS = 'fortune_note_ids_';
    /**
     * 运势笔记详情
     */
    const REDIS_KEY_FORTUNE_NOTE_DETAIL = 'fortune_note_detail_';

    /**
     * 获取档案的运势笔记
     * @param array $map
     * @return array|bool|false|mixed|\PDOStatement|string|\think\Collection
     */
    public function getRidNote($map = [])
    {
        $rid = $map['rid'];

        $times = false;

        if (intval($this->cache_on >= 1) && Cache::has('fortune_note_' . $rid))
        {
            $times = Cache::get('fortune_note_' . $rid);
        }

        if ($times === false)
        {
            try
            {
                $times = $this
                    ->select('time')
                    ->where('rid', $rid)
                    ->get();

                $times = json_decode(json_encode($times, true), true);
            }
            catch (\Exception $e)
            {
                $times = [];
            }
            if ($this->cache_on >= 1)
            {
                Cache::set('fortune_note_' . $rid, $times, 86400 * 7);
            }
        }
        return $times;
    }

    /**分页获取列表
     * @param array $map
     * @return array|string
     */
    public function getListPage($map = [])
    {
        //获取 用户所有运势日记的id
        $note_ids = false;
        // if (intval($this->cache_on >= 1) && Cache::has(self::REDIS_KEY_FORTUNE_NOTE_IDS . $map['rid']))
        // {
        //     $note_ids = Cache::get(self::REDIS_KEY_FORTUNE_NOTE_IDS . $map['rid']);
        // }
        if ($note_ids === false)
        {
            try
            {
                $note_ids = $this
                    ->select('id')
                    ->where(['rid' =>$map['rid']])
                    //->where('status','!=', config('code.status_delete'))
                    ->orderBy('id','DESC')
                    ->get();
                   
            }
            catch (\Exception $e)
            {
                // 错误信息写入日志
                \Log::info('获取用户运势日记ids错误:' . '[' . $map['rid'] . ']');
            }
            //获取数据
            $note_ids = json_decode(json_encode($note_ids, true), true);

            //存储所有ids
            $cache_data = '';
            foreach ($note_ids as $k => $v)
            {
                $cache_data .= ',' . $v['id'];
            }
            if ($this->cache_on >= 1)
                Cache::set(self::REDIS_KEY_FORTUNE_NOTE_IDS . $map['rid'], $note_ids, $this->cache_time);
        }

        //进行分页返回数据
        $total = count($note_ids);//统计有多少个id
        $data_list = getPaginatorData($total, $map['page']);//获取数据分页信息
        $result = array_slice($note_ids, $data_list['start'], $data_list['per_page']);//获取分页后的id数组
        unset($data_list['start']);
        unset($data_list['end']);

        $data_list['data'] = $this->getDetails($result);

        return $data_list;
    }


    /**
     * 获取所有的详情
     * @param $all_list
     * @return array|false|mixed|\PDOStatement|string|\think\Collection
     */
    public function getDetails($all_list = [])
    {  
        $result = [];
        $ids = $this->getAllNotCachedIds($all_list, self::REDIS_KEY_FORTUNE_NOTE_DETAIL);
        try
        {
            if (strlen($ids) > 0)
            {
                $result = $this
                    ->select('id','rid','time','state','mood','content','from','create_time')
                    ->whereIn('id',explode(',', $ids))
                    ->orderBy('id','DESC')
                    ->get();
                $result = json_decode(json_encode($result, true), true);
                if ($this->cache_on >= 1)
                    foreach ($result as $v)
                        Cache::set(self::REDIS_KEY_FORTUNE_NOTE_DETAIL . $v['id'], $v, $this->cache_time);

            }
            if (intval($this->cache_on >= 1) && Cache::has(self::REDIS_KEY_FORTUNE_NOTE_DETAIL . $v['id'])) //如果缓存打开，循环获取，因为缓存里已经有了数据
            {
                $result = [];
                foreach ($all_list as $v)
                    $result[] = Cache::get(self::REDIS_KEY_FORTUNE_NOTE_DETAIL . $v['id']);
            }

        }
        catch (\Exception $e)
        {
            // 错误信息写入日志
            \Log::info('获取用户运势日记详情错误:' . '[' . $ids . ']');
        }

        return $result;
    }

    /**
     * 保存运势笔记
     * @param array $map
     * @return array|bool|\think\response\Json
     */
    public function saveFortuneNote($map = [])
    {
        if (trim($map['content']) == '') {
            return show(config('code.error'), '内容不能为空');
        }
        try {

            $id = $this->table('fortune_note')->insertGetId($map);
            Cache::forget('fortune_note_ids_' . $map['rid']);//删除运势日记ids
            Cache::forget('fortune_note_' . $map['rid']);
        } catch (\Exception $e) {
            $this->error = '保存日记失败';
            return false;
        }

        $array = [
            'id' => $id,
            'create_time' => date('Y-m-d H:i:s', $map['create_time']),
            'content' => $map['content'],
            'state' => $map['state'],
            'mood' => $map['mood'],
            'from' => [
                'rid' => $map['rid'],
                'time' => date('Y-m-d', $map['time']),
                'remark' => '每日运势',
                'icon_url' => config('fortune.thumb'),
            ],
        ];

        return $array;
    }

}